package org.kojo.tdrm.utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class HttpUtils {
	private static Logger log = Logger.getLogger(HttpUtils.class.getName());
	String type = "application/x-www-form-urlencoded";
	
	public String getUrlContent(String url) throws IOException{
		return this.requestUrlContent(url,"GET");
	}
	public String postUrlContent(String url) throws IOException{
		return this.requestUrlContent(url,"POST");
	}
	public String requestUrlContent(String url,String method) throws IOException {
		log.finer(method+": HttpUtils->"+url);
		String content = "";
		byte[] contents = new byte[1024];
		URL u = new URL(url);
		HttpURLConnection conn = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		try {
			conn = (HttpURLConnection) u.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod(method);
			conn.setRequestProperty("Content-Type", type);
			is = conn.getInputStream();
			bis = new BufferedInputStream(is);
			int bytesRead = 0;
			while ((bytesRead = bis.read(contents)) != -1) {
				content += new String(contents);
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			this.closeInputStream(bis);
			this.closeInputStream(is);
			this.closeConn(conn);
		}
		return content;
	}
	
	public Map<String, String> getQueryMap(String query) {
		String[] params = query.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String param : params) {
			String name = param.split("=")[0];
			String value = param.split("=")[1];
			map.put(name, value);
		}
		return map;
	}
	
	private void closeConn(URLConnection conn) {
		//
	}
	private void closeInputStream(InputStream is){
		if(is!=null){
			try {
				is.close();
			} catch (IOException e) {
				//donoting
			}
		}
	}
}
